module.exports = app=>{
  const sendMail = require('./email')

  const randomFns=()=> { // 生成6位随机数
      let code = ""
      for(let i= 0;i<6;i++){
          code += parseInt(Math.random()*10)
      }
      return code 
  }
  const regEmail=/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ //验证邮箱正则
  const formidable = require('formidable');
  return async(req,res,next)=>{
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var email_content = {
        title: '',
        content: ''
      };
      if(fields.type==='signin'){
        email_content.title = '验证你的电子邮件',
        email_content.content = '您正在注册涅槃之路网站账号'
      } else if(fields.type === 'bindEmail') {
        email_content.title = '验证你的电子邮件',
        email_content.content = '您正在为涅槃之路网站绑定邮箱'
      } else {
        email_content.title = '验证你的电子邮件',
        email_content.content = '您正在修改涅槃之路网站账号信息'
      }
      let EMAIL=fields.email
      if (regEmail.test(EMAIL)){
        let code=randomFns()
        sendMail(
          EMAIL,
          email_content.title, // 标题
          `<p>您好！</p>
          <p>${email_content.content}</p>
          <p>您的验证码是：<strong style="color: #ff4e2a;">${code}</strong></p>
          <p>***该验证码5分钟内有效***</p>
          <p>如非本人操作请尽快修改账号密码！</p>`, // html 内容
          async (e) => {
            if(e === true) {
              const Code = require("../models/verifyCode")
              const email = EMAIL
              try{
                await Code.deleteMany({email})
                await Code.create({email, code})
                setTimeout(async ()=>{    //5分钟后失效
                    await Code.deleteMany({email})
                },1000*60*5)
                res.json({
                  'state': true, 
                  'msg': true
                });
              } catch(err){
                res.json({
                  'state': false, 
                  'msg': '验证码生成失败'
                });
              }
            } else {
              res.json({
                state: false,
                'msg': '验证码获取失败'
              });
            }
          }
        )        
      }else{
        res.json({
          state: false,
          msg: '请输入正确的邮箱格式！'
        })
      }
    })
  }
}